//
//  RecordViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/18/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "RecordViewController.h"
#import "PublicMethodEngine.h"


#import "NavTitleView.h"
#import "UploadManagerEngine.h"


#import "SinaShareMethod.h"

static ASIHTTPConnection *createThread_connect;

static int charaterNum = 0;

@interface RecordViewController (){
    
    int threadID;
    BOOL isAddComment;
}

@end



@implementation RecordViewController

@synthesize photoImage;

@synthesize photoUIView;



@synthesize dateStr;
@synthesize photoDateStr;

@synthesize locationNameStr;

@synthesize theBodyString;

@synthesize imageView;

- (void)dealloc
{

    if (createThread_connect != nil) {
        createThread_connect.connectionDelegate = nil;
        [createThread_connect release];
        createThread_connect = nil;
    }
    
    [addCommentLable release];
    
    [textBgView release];
    [recordUploadArray release];
    
    [photoImage release];
    
    [imageView release];
    
    [photoUIView release];
    
    
    [dateStr release];
    
    [theBodyString release];

    [recordView release];
    [bottomView release];
    [toolsView release];
    
    [locationAdderssLabel release];
    
    [recordTextView release];
    
    [inputSourceButton release];
    [inputSourceShowButton release];
    
    [myScrollView release];
    
    [charaterNum release];
    
    [sinaShareButton release];

    [publicList release];
    
    [locationNameStr release];

    [signAnniversaryImageView release];
    
    
    
       
    CLog(@"Record view dealloc");
    
    [super dealloc];
}


- (id)initWithThreadID:(int)threadId{
    
    self = [super init];
    if (self) {
        
        threadID = threadId;
    }
    
    return self;
}


- (id)initWithImage:(UIImage *)image
{
    [super init];

    photoImage = image;
    
    return self;
}

- (id)initWithImage:(UIImage *)image photoDate:(NSString *)dateStrParam
{
    [super init];
    
    photoImage = image;
    photoDateStr = [[NSString alloc] initWithFormat:@"%@", dateStrParam];
    
    CLog(@"Record init with photodate %@", photoDateStr);
    
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [recordTextView becomeFirstResponder];
    
    self.title = @"发起话题";
    
    textBgView.layer.cornerRadius = 3;
    
    textBgView.layer.shadowOpacity = 0.4;
	textBgView.layer.shadowRadius = 1.5;
	textBgView.layer.shadowOffset = CGSizeMake(0, 0);
    CGRect shadowFrame = textBgView.layer.bounds;
    CLog(@"shadow frame rect %f, %f, %f, %f", shadowFrame.origin.x, shadowFrame.origin.y, shadowFrame.size.width, shadowFrame.size.height);
    CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(shadowFrame.origin.x, shadowFrame.origin.y, shadowFrame.size.width, shadowFrame.size.height +2)].CGPath;
    textBgView.layer.shadowPath = shadowPath;
   
    [self navigationBarInit];
    
    publicRate = 0;
    locationNameStr = nil;
    
    if (publicList == nil) {
        publicList = [[NSMutableArray alloc]init];
    }
    
    if (threadID > 0) {
        
        recordTextView.text = @"转发微博";
        isAddComment = false;
        sinaShareButton.hidden = NO;
        addCommentLable.hidden = NO;
        
    }
    
    imageView.layer.shadowColor = [[UIColor grayColor] CGColor];
    imageView.layer.shadowOffset = CGSizeMake(0, 1);  
    
    [self registerForKeyboardNotifications];
    
    //[recordTextView becomeFirstResponder];
    
    bottomView.backgroundColor = BackGround_Color;
    
    //默认家人可见需要在家人数据获取后添加
//    UIImageView *familyView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
//    familyView.image = [UIImage imageNamed:@"peopleBG_iphone.png"];
//    [familyView setContentMode:UIViewContentModeScaleToFill];
//    [myScrollView addSubview:familyView];
//    
//    [[photoUIView layer] setShadowOffset:CGSizeMake(1, 1)];
//    [[photoUIView layer] setShadowRadius:2];
//    [[photoUIView layer] setShadowOpacity:1]; 
//    [[photoUIView layer] setShadowColor:[UIColor grayColor].CGColor];
//    
//    
//    UILabel *familyLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
//    familyLabel.text = @"家人";
//    familyLabel.backgroundColor = [UIColor clearColor];
//    familyLabel.textColor = [UIColor blackColor];
//    [familyLabel setTextAlignment:UITextAlignmentCenter];
//    [familyView addSubview:familyLabel];
//    
//    [familyView release];
//    [familyLabel release];
     
       
}


- (void)viewWillAppear:(BOOL)animated{
    
          
  [recordTextView becomeFirstResponder];
      
    [super viewWillAppear:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    CLog(@"Record View Will disappear");
   
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    photoImage = nil;
    
    self.photoUIView = nil;
    self.imageView = nil;
    
       
    [textBgView release];
    textBgView = nil;
    
    [recordView release];
    recordView = nil;
    
    [bottomView release];
     bottomView = nil;
    
    [myScrollView release];
    myScrollView = nil;
    
    [recordTextView becomeFirstResponder];
    
    CLog(@"viewDidUnload");
    
}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [self navigationBarInit];
//}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark -
#pragma mark Connection Delegate


- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
    
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/mobile/diary/family?tid=%d",BASEURL, tid]])
    {
        CLog(@"dict %@", dict);
        NSDictionary *objectDict = [dict objectForKey:@"object"];
       
        NSArray *array = [objectDict objectForKey:@"result"];

       
    }
}
    
- (void)connectionArrayError:(NSError *)error
{
    CLog(@"PublicSelectionView Error %@", error);
}


#pragma mark -
#pragma mark Record Method 记录内容处理


- (IBAction)signForAnniversary:(id)sender{
    
    if (_isSignForAnniversary) {
        _isSignForAnniversary = NO;
        
        signAnniversaryImageView.hidden = YES;
        
    }
    else{
        
        if (imageView.image) {
            
               _isSignForAnniversary = YES;
            signAnniversaryImageView.hidden = NO;
        }        
        else{
            
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"要先添加照片才能标记为大事件哦！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"取消" otherButtonTitles:nil];
            
                       [alert show];
            [alert release];

            
        }
        
     
        
    }
    
}


- (void)postAnniversary{
    
    
    [recordTextView resignFirstResponder];
    [self inputSourceHidePosition];
    
    
    NSString *recordText = recordTextView.text;
    recordText = [recordText stringByReplacingOccurrencesOfString:@"'" withString:@"&acute;"];
    
    NSDate *zoneDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
    NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
    NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
    
    NSTimeInterval _interval = [nd timeIntervalSince1970];
    long long int date = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
    
    NSString *localName = @"";
    
    
    if (locationNameStr != nil) {
        localName = locationNameStr;
    }
    else{
        localName = @"null";
    }
    
    
    //base64编码 图片
    NSString *imageString;
//    if(imageView.image){
//        imageString=[Photo image2String:imageView.image];
//    }
    imageString = @"null";
    
    
    NSDictionary *theRequestDictionary;
    
    int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
    int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
    
    NSArray *keys ;
    NSArray *objects ;
    
    
    NSMutableString *accessList = [[NSMutableString alloc] init];
    
    for (int i = 0;i<publicList.count;i++) {
        
        if (i<publicList.count-1) {
            
            [accessList appendString:[NSString stringWithFormat:@"%@,",[publicList objectAtIndex:i]]];
        }
        else{
            [accessList appendString:[NSString stringWithFormat:@"%@",[publicList objectAtIndex:i]]];
        }
        
    }
    
    if ([accessList isEqualToString:@""]) {
        [accessList appendString:@"null"];
    }
    
    
    if(imageView.image){
        keys = [NSArray arrayWithObjects:@"tid", @"activityType", @"activityContent", @"activityDate", @"uid",@"deviceId",@"fileData",@"fileName",@"notifyUsers",nil];
        
        
        
        objects  = [NSArray arrayWithObjects:[NSNumber numberWithInt:tid],@"event", recordText, [NSNumber numberWithLongLong:date],[NSNumber numberWithInt:uid] , [NSNumber numberWithInt:3], imageString,@"fileName",accessList,nil];
        
        
    }
    
    else{
               
        [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"要先给宝宝添加照片才能标记为大事件哦！"];
        
        return;
    }
    
      
    theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    CLog(@"theRequestDictionary %@", theRequestDictionary);
    
   NSString *jsonStr = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    [self saveAnniversaryData:jsonStr];
       
    
   // NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];;
	
	//NSMutableURLRequest * request = [WebRequest createActivityRequestWith:jsonData];
	
		
   // activityCreate_connection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
 
    
    
}


- (void)postRecordAction:(id)sender
{
    
    if (recordTextView.text == nil || recordTextView.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"微博内容不能为空"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;

    }
    
    else if (recordTextView.text.length > 140) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"微博内容不能超过140个字"
							  
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
        [alert release];
        return;

        
    }
    
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    int userId = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CreateMicroBlogThread.aspx",BASEURL,userName];
    
	    
    NSArray *keys = [NSArray arrayWithObjects:@"Author",@"Body",@"HasPhoto",@"UserID", nil];
    
    NSArray *objects = [NSArray arrayWithObjects:userName,recordTextView.text,@"false",[NSNumber numberWithInt:userId], nil];
    
    //转发微博
    if (threadID > 0) {
        
       keys = [NSArray arrayWithObjects:@"Author",@"Body",@"HasPhoto",@"UserID",@"ForwardedThreadID", nil];
       objects = [NSArray arrayWithObjects:userName,recordTextView.text,@"false",[NSNumber numberWithInt:userId],[NSNumber numberWithInt:threadID], nil];

        urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/ForwardMicroBlog.aspx?addcomment=%d",BASEURL,userName,isAddComment];

        
    }
    
    NSURL *url = [NSURL URLWithString:urlString];
    

    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *bodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", bodyString);
    
    //  //
    NSData *_jsonData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (createThread_connect != nil) {
        createThread_connect.connectionDelegate = nil;
        [createThread_connect release];
        createThread_connect = nil;
    }
    createThread_connect = [[ASIHTTPConnection alloc]initPOSTWithURL:url jsonData:_jsonData resultDict:YES];
    createThread_connect.connectionDelegate = self;
    [createThread_connect startAsynchronous];
    
    [recordTextView resignFirstResponder];
    
}



//输入验证
- (BOOL)isInputRight{
    
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Faild!" message:@"上传病史功能稍后向您开发，感谢支持！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return NO;
        
        
    }
    
    if (recordTextView.text.length > 140) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"文字描述不能超过140字！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return NO;
        
        
    }
    
    if (!imageView.image && recordTextView.text.length == 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"发布内容不能为空！" 
                                                       delegate:self 
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        return NO;

    }
    
    return YES;
    
}





#pragma mark connection delegate

- (void)connectionSuccess:(NSDictionary *)dict{
    
    if ([dict isMemberOfClass:[NSNull class]]) {
        
        [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"请求失败" ];
        return;
    }
    
    [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"发布成功" ];
    
    CLog(@"uopload success");
    
    
     recordTextView.text = @"";
     imageView.image = nil;
     charaterNum.text = @"0/140";

    
   // [self performSelector:@selector(toTimelineView) withObject:nil afterDelay:0.5];
}

- (void)connectionError:(NSError *)error{
	CLog(@"error info");
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"哎呀，网络好像有问题！" duration:DEFAULT_LOADING_TIME *1.2];
    
    
}

- (void)postSuccess:(NSString *)postinfo{
    
}



#pragma mark  上传数据

-(void)saveRecordData:(NSString *)theBodyString{
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    int userId = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CreateMicroBlogThread.aspx",BASEURL,userName];
    
	NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSArray *keys = [NSArray arrayWithObjects:@"Author",@"Body",@"HasPhoto",@"UserID", nil];
    
    NSArray *objects = [NSArray arrayWithObjects:userName,recordTextView.text,false,[NSNumber numberWithInt:userId], nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *bodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", bodyString);
    
    //  //
    NSData *_jsonData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
   
    if (createThread_connect != nil) {
        createThread_connect.connectionDelegate = nil;
        [createThread_connect release];
        createThread_connect = nil;
    }
    createThread_connect = [[ASIHTTPConnection alloc]initPOSTWithURL:url jsonData:_jsonData resultDict:YES];
    createThread_connect.connectionDelegate = self;
    [createThread_connect startAsynchronous];
            
    recordTextView.text = @"";
    imageView.image = nil;
    charaterNum.text = @"0/140";
    
}


#pragma mark ASIhttp conect delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    [LoadingView hideWithAnimated:NO];
    NSString *urlStr = [url absoluteString];
    NSRange range = [urlStr rangeOfString:@"CreateMicroBlogThread"];
    if (range.length > 0) {
        
        if ([[dict objectForKey:@"isSuccess"] boolValue]) {
         
                [BlogMainViewViewController  setRefType:KMicroBlogRefTypeNew];
                [self dismissModalAction:nil];
                     
        }
    else{
        
        [LoadingView showDurationMessageLoadingViewWith:2 message:[dict objectForKey:@"messageContent"]];
    }
        
    }
    
    range = [urlStr rangeOfString:@"ForwardMicroBlog"];
    if (range.length > 0) {
        
        if ([[dict objectForKey:@"isSuccess"] boolValue]) {
            
            [BlogMainViewViewController  setRefType:KMicroBlogRefTypeNew];
            [self dismissModalAction:nil];
            
        }
        else{
            
            [LoadingView showDurationMessageLoadingViewWith:2 message:[dict objectForKey:@"messageContent"]];
        }
        
    }

    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
   // [LoadingView showDurationMessageLoadingViewWith:2 message:@"网络不给力，请稍后重试！"];
    [BlogMainViewViewController  setRefType:KMicroBlogRefTypeNew];
    [self dismissModalAction:nil];
    
}



- (void)tryUpload{
    
    
    NSString *sql = @"select id, json, url, uid, tid,time from LocalRecord";
    
    if (recordUploadArray == nil) {
        recordUploadArray = [[NSMutableArray alloc]init];
    }    
    else{
        
        
        [recordUploadArray removeAllObjects];
        
    }
    
    NSArray *keyValue = [NSArray arrayWithObjects:@"id", @"json", @"url", @"uid", @"tid", @"time", nil];
    NSArray *array = [[PublicDatabaseEngine sharedDatabaseEngine] searchWithSQL:sql select:keyValue];
    
    CLog(@"recordUploadArray count %d", [array count]);
    
    [recordUploadArray addObjectsFromArray:array];
    
    if (recordUploadArray != nil && [recordUploadArray count] > 0) {
        
        [self uploadRecordData];
    }

    
    
   // [self sendRecordData:self.theBodyString];
    
}


- (void)uploadRecordData{
    
     if (recordUploadArray != nil && [recordUploadArray count] >0){
        
        NSDictionary *dict = [recordUploadArray objectAtIndex:0];
        
        CLog(@"upload locale id %d", [[dict objectForKey:@"id"] intValue]);
              
            
        NSString *jsonString = [dict objectForKey:@"json"];
         
         CLog(@"local jsonString %@", jsonString); 
        
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        
       NSMutableURLRequest * request = [WebRequest diaryCreateRequestWith:jsonData];        
        CLog(@"request %@", request);
        
        NSError *err=nil;
        NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                                   returningResponse:nil 
                                                               error:&err];
        if(returnData==nil)
        {
            //if([err code])
            
            CLog(@"Code:%d,domain:%@,localizedDesc:%@",[err code],
                 [err domain],[err localizedDescription]);
        }
        else
        {
            CLog(@"uopload success");
            
            NSInteger databaseId = [[dict objectForKey:@"id"] intValue];
            
            NSString *sql = [NSString stringWithFormat:@"delete from LocalRecord where id = %d", databaseId];
            
            BOOL isDelete = NO;
            
            while (!isDelete) {
                isDelete = [[PublicDatabaseEngine sharedDatabaseEngine] executeSQL:sql];
                [[SDDataCache sharedDataCache:kImageCache_Locale_Record] removeDataForKey:[dict objectForKey:@"time"]];
            }
            
            CLog(@"returnData %@", returnData);
        }
        
        [recordUploadArray removeObject:dict];
    }
    
}




#pragma mark 保存为大事件
- (void)saveAnniversaryData:(NSString *)jsonStr{
    
    NSString *imagePath;
    
    //把图片本地存成文件
    if (imageView.image) {
        
        NSData* pictureData = [[PublicMethodEngine sharedPublicMethodEngine] compresImageDataWith:imageView.image maxPix:PHOTO_MAXPIX];
        
        // NSData* pictureData = UIImagePNGRepresentation(photoImageView.image);
        
        // [[SDDataCache sharedDataCache:kImageCache_Content_Icon] storeData:pictureData forKey:self.dateStr];
        
        imagePath = [NSString stringWithFormat:@"%@_anniversary",self.dateStr];
        
        [[SDDataCache sharedDataCache:kImageCache_Locale_Record] storeData:pictureData forKey:imagePath ];
        
        
    }

    
      
    NSString *sql = @"";
    
    int tid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"] intValue];
    int uid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"userId"] intValue];
    
    NSString *url = [NSString stringWithFormat:@"%@/mobile/activity/create",BASEURL];
    
    
    NSString *newsql = [NSString stringWithFormat:@"insert or replace into local_anniversary (json,url,uid, tid, time) values ('%@','%@',%d,%d, '%@');",jsonStr, url, uid, tid,imagePath];
    
    sql = [sql stringByAppendingString:newsql];
    
    
    CLog(@"insert sql %@", sql);
    if ([sql length] >0) {
        
        NSInteger recordId = 0;
        int insertCount = 0;
        //
        while (recordId == 0 && insertCount <2) {
            recordId = [[PublicDatabaseEngine sharedDatabaseEngine] insertOrReplaceWithSQL:sql]; 
            insertCount++;
        }
        
        if (recordId >0) {
            //本地记录保存后启动上传
            [[UploadManagerEngine sharedUploadManagerEngine] newAnniversaryAction];
         
        }
        else {
            //记录存储错误，需要提示重存，可能性很小
        }
        
        
    }
    
    
}


#pragma mark -
#pragma mark Camera

- (IBAction)takePhoto:(id)sender
{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]init];
    actionSheet.delegate = self;
    
    
    [actionSheet addButtonWithTitle:@"从相册选择"];
    [actionSheet addButtonWithTitle:@"拍照"];
    [actionSheet addButtonWithTitle:@"取消"];
    [actionSheet setCancelButtonIndex:2 ];
    
    [actionSheet showInView:self.view];
    
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        
        [self showPhotoLibrary:nil];        
        
    }
    if (buttonIndex == 1) {
        
        [self showCamera:nil];
        
    }
    
    
    [actionSheet release];
} 

- (IBAction)showCamera:(id)sender
{
	[LoadingView showDefaultLoadingView];
	
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		//imagePickerController.allowsImageEditing = YES;
		[self presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
		
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		[self presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
		imagePickerController.allowsEditing = YES;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		[self presentModalViewController:imagePickerController animated:YES];
		[imagePickerController release];
	}
	
	[LoadingView hideWithAnimated:YES];
}


- (IBAction)showPhotoLibrary:(id)sender
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		
		[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(showPhotoLibrary) userInfo:nil repeats:NO];
	}
	
}

-(void)showPhotoLibrary
{
	UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
	//imagePickerController.mediaTypes = [NSArray arrayWithObjects:(NSString*)kUTTypeImage,(NSString*)kUTTypeMovie,nil];
	imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
	imagePickerController.delegate = self;
	imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
	
	[self presentModalViewController:imagePickerController animated:YES];
	[imagePickerController release];
}

#pragma mark delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     CLog(@"Media editingInfo %@ \n ", info);
    
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        [picker dismissModalViewControllerAnimated:YES];
        
        UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        if (img != nil) {
            
            //如果是 来自照相机的image，那么先保存
            UIImageWriteToSavedPhotosAlbum(img, nil,  nil, nil); 

            
            UIImage *newImage = [[PublicMethodEngine sharedPublicMethodEngine] compresImageWith:img maxPix:PHOTO_MAXPIX];
            
            CLog(@"image size x:%f, y:%f", newImage.size.width, newImage.size.height);
            
            //照片时间获取
            NSDictionary *metadataDict = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];
            
            long long int dateInt;
            //防止低版本获取不到信息, iOS4.1 or later!
            if (metadataDict == nil) {
                NSDate *zoneDate = [NSDate date];
                NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
                NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
                
                NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
                
                NSTimeInterval _interval = [nd timeIntervalSince1970];
                dateInt = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
            }
            else {
                NSDictionary *ExifDict = [metadataDict objectForKey:@"{Exif}"];
                CLog(@"ExifDict %@", ExifDict);
                NSString *originalDate = [ExifDict objectForKey:@"DateTimeOriginal"];
                
                NSDate *zoneDate = [NSDate date];
                NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
                NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
                
                CLog(@"Photo date %@", originalDate);
                if (originalDate == nil) {
                    
                    NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
                    
                    NSTimeInterval _interval = [nd timeIntervalSince1970];
                    dateInt = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
                }
                else {
                    NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
                    
                    CLog(@"nd date %@", nd);
                    originalDate = [originalDate stringByReplacingCharactersInRange:NSMakeRange(4, 1) withString:@"-"];
                    originalDate = [originalDate stringByReplacingCharactersInRange:NSMakeRange(7, 1) withString:@"-"];
                    
                    CLog(@"Photo date %@", originalDate);
                    
                    NSDate *photoDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:originalDate];
                    
                    CLog(@"Photo date %@", photoDate);
                    
                    NSTimeInterval _interval = [photoDate timeIntervalSince1970];
                    dateInt = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000;
                }
            }
            
            
            if (photoDateStr != nil ) {
                [photoDateStr release];
            }
            
            photoDateStr = [[NSString alloc]initWithFormat:@"%lld", dateInt];
            
            
            if (photoUIView.hidden) {
                photoUIView.hidden = NO;
                imageView.image= newImage;
            }
            else {
                imageView.image= newImage;
                //[newImage release];
            }
            
            [newImage release];
        }

    }
    else {
        
        [picker dismissModalViewControllerAnimated:YES];
        
        
        UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        if (img != nil) {
            UIImage *newImage = [[PublicMethodEngine sharedPublicMethodEngine] compresImageWith:img maxPix:PHOTO_MAXPIX];
            
            CLog(@"image size x:%f, y:%f", newImage.size.width, newImage.size.height);
            
            if (photoUIView.hidden) {
                photoUIView.hidden = NO;
                imageView.image= newImage;
            }
            else {
                imageView.image= newImage;
            }
            
            [newImage release];
            
        }
        
        NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:referenceURL resultBlock:^(ALAsset *asset)
         {
             CLog(@"Asset %@", asset);
             //照片时间
             NSDate *photoDate = [asset valueForProperty:ALAssetPropertyDate];
             NSDate *zoneDate = [NSDate date];
             NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
             NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
             long long int dateInt;
             
             if (photoDate == nil) {
                 
                 NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
                 
                 NSTimeInterval _interval = [nd timeIntervalSince1970];
                 dateInt = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
             }
             else {
                 NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
                 
                 CLog(@"nd date %@", nd);
                 
                 CLog(@"Photo date %@", photoDate);
                 
                 NSTimeInterval _interval = [photoDate timeIntervalSince1970];
                 dateInt = (long long int)(_interval -interval)*1000;
             }
             
             if (photoDateStr != nil ) {
                 [photoDateStr release];
             }
             
             photoDateStr = [[NSString alloc]initWithFormat:@"%lld", dateInt];
    
         }
                failureBlock:^(NSError *error)
         {
             // error handling
             CLog(@"Error info %@", error);
             
             //获取相册失败只能使用当前时间
             NSDate *zoneDate = [NSDate date];
             NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
             NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
             long long int dateInt;

             NSDate *nd=[NSDate dateWithTimeIntervalSinceNow:interval];
             
             NSTimeInterval _interval = [nd timeIntervalSince1970];
             dateInt = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 
             
             if (photoDateStr != nil ) {
                 [photoDateStr release];
             }
             
             photoDateStr = [[NSString alloc]initWithFormat:@"%lld", dateInt];
             
             
             if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]]) {
                 UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"请启动“定位服务”来获取完整图片信息" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
                 [alert show];
                 [alert release];
                 alert.tag  = 120;
             }
             else {
                 UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"请启动“定位服务”来获取完整图片信息" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                 [alert show];
                 [alert release];
             }
         }];
        [library release];
    }
    
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {

    CLog(@"image editingInfo %@ \n ", editingInfo);
    
    UIImage *newImage = [[PublicMethodEngine sharedPublicMethodEngine] compresImageWith:image maxPix:PHOTO_MAXPIX];
    
    CLog(@"image size x:%f, y:%f", newImage.size.width, newImage.size.height);
	
    
    [picker dismissModalViewControllerAnimated:YES];
    
    if (photoUIView.hidden) {
        photoUIView.hidden = NO;
        imageView.image= newImage;
    }
    else {
        imageView.image= newImage;
    }
    
    [newImage release];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	
    
	[picker dismissModalViewControllerAnimated:YES];
	
}


#pragma mark Photo Rot
- (IBAction)photoRotAction:(id)sender
{
    UIImage *image = imageView.image;
    
    if (image) {
        PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];
        
        UIImage *newImage = [methodEngine rotImageRightOrLeft:image isRight:YES];
        
        imageView.image = newImage;
        [newImage release];
    }

}

#pragma mark -
#pragma mark 地理位置

- (IBAction)AddLocation:(id)sender
{
    
    LocationEngine *locaionEngine = [LocationEngine sharedLocationEngine];
    
    // [locaionEngine  startCheckingLocation];
    locaionEngine.locationDelegate = self;
    
    CLog(@"locationState %@", locaionEngine.locationState);
    if ([locaionEngine.locationState isEqualToString:@"Done"]) {
        CLog(@"location done");

        //latitude = locaionEngine.latitude;
        //longitude = locaionEngine.longitude;
        
        
        //CLog(@"location name : %@", locaionEngine.locationName);
        
        locationAdderssLabel.text = locaionEngine.locationName;
        //	[LoadingView hideWithAnimated:YES];
        
    }
    else {
        CLog(@"location un done");
        
        locationAdderssLabel.text=@"正在获取..."; 
        [locaionEngine startCheckingLocation];
        
    }
    
    
	
    
}

-(void)LocationDone{
    
    LocationEngine *locaionEngine = [LocationEngine sharedLocationEngine];
    
    if ([locaionEngine.locationState isEqualToString:@"Done"]) {
        CLog(@"location done");
        
        //latitude = locaionEngine.latitude;
        //longitude = locaionEngine.longitude;
        
        
        //CLog(@"location name : %@", locaionEngine.locationName);
        
        locationAdderssLabel.text = locaionEngine.locationName;
        locationNameStr = locaionEngine.locationName;
        [LoadingView hideWithAnimated:YES];
        
    }
    else{

        locationAdderssLabel.text = @"获取失败";
    }
    
    
    [LoadingView hideWithAnimated:YES];
    
}



#pragma mark -
#pragma mark UINavigateBar
- (void)navigationBarInit
{

    UIView *titleView = [[NavTitleView alloc] initWithTitle:@"发起话题"];
    self.navigationItem.titleView = titleView;
    [titleView release];
    
    
    if( iOS7) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.navigationController.navigationBar.translucent = NO;
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
        
    }
    else{
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
    }

    
    //定义右侧按钮
//    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
//    [rightButton addTarget:self action:@selector(postRecordAction:) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
//    [rightButton release];
    
    
    UIButton *rightBt = [[UIButton alloc]initWithFrame:CGRectMake(0, 7, 50, 30)];
    [rightBt.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [rightBt.titleLabel setTextColor:[UIColor whiteColor]];
    [rightBt setTitle:@"发送" forState:UIControlStateNormal];
   // [rightBt addTarget:self action:@selector(postRecordAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:rightBt];
    [self.navigationItem setRightBarButtonItem:rightButton];
    [rightBt release];
    [rightButton release];

    
    UIButton *leftBt = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftBt setImage:[UIImage imageNamed:@"icon_return.png"] forState:UIControlStateNormal];
    [leftBt addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:leftBt];
    [self.navigationItem setLeftBarButtonItem:leftButton];
    [leftBt release];
    [leftButton release];
    
    
 
}

- (void)backAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    CLog(@"alert button clicked index %d", buttonIndex);
    switch (alertView.tag) {
        case 110:
        {
            switch (buttonIndex) {
                case 0:
                {
                    [self dismissModalViewControllerAnimated:YES];
                    break;
                }
                case 1:
                {
                    
                    break;
                }
                default:
                    break;
            }
            break;
         
        }
        case 120:
        {
            switch (buttonIndex) {
                case 0:
                {

                    break;
                }
                case 1:
                {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]]; 
                    break;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }

}


#pragma mark - 
#pragma mark UITextView Delegate


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    CLog(@"textViewShouldBeginEditing");
    if ([textView.text isEqualToString:@"记录孩子点滴"]) {
        textView.text = @"";
    }
       
   
    
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    CLog(@"textViewShouldEndEditing");
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    CLog(@"textViewDidBeginEditing");
    
    [self inputSourceShowPosition];
    
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    CLog(@"textViewDidEndEditing");
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    //当检测到有回车输入时即为点击了Done按钮，收起键盘
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        
        [self inputSourceHidePosition];
        return NO;
    }

    return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    CLog(@"textViewDidChange");
    
    if (textView.text) {
        
          charaterNum.text = [NSString stringWithFormat:@"%d/140",textView.text.length];
        
        if (textView.text.length > 140) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"文字描述不能超过140字！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            
                }
       
    }
    
      
    
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    CLog(@"textViewDidChangeSelection");
}

#pragma mark -
#pragma mark 隐私 Secret

- (IBAction)secretSetAction:(id)sender
{
    
    
    CLog(@"隐私设置！");
}




#pragma mark -
#pragma mark 键盘 表情

static BOOL  emojiShow = NO;

- (IBAction)showInputSourceAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    NSInteger tag = button.tag;

    
    if (tag == 0) {
        if (emojiShow) {
            emojiShow = !emojiShow;
            [self showEmojiBoard:inputSourceButton];
        }
        else {
            [recordTextView becomeFirstResponder];
        }
        [self inputSourceShowPosition];
        

    }
    else {
        [recordTextView resignFirstResponder];

        [self inputSourceHidePosition];
        
    }
 
}

- (void)inputSourceShowPosition
{
    inputSourceShowButton.tag = 1;
    [inputSourceShowButton setImage:[UIImage imageNamed:@"icon_down_iphone.png"] forState:UIControlStateNormal];

    
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion < 5.0) {
        CGSize bottomSize = CGSizeMake(320, 215 +toolsView.frame.size.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }

}
- (void)inputSourceHidePosition
{
    inputSourceShowButton.tag = 0;
    [inputSourceShowButton setImage:[UIImage imageNamed:@"icon_up_iphone.png"] forState:UIControlStateNormal];
    
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion < 5.0) {
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    
}



#pragma mark keyboard 键盘监听
- (void) registerForKeyboardNotifications{
    
    //iOS 5.0键盘事件监听
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    
}

- (void) keyboardWasChange:(NSNotification *) notif{
    if (!emojiShow) {
        NSDictionary *info = [notif userInfo];
        
        NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [value CGRectValue].size;
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height + keyboardSize.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    else {
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    
}

- (void) keyboardWasShown:(NSNotification *) notif{
    
    if (!emojiShow) {
        NSDictionary *info = [notif userInfo];
        
        NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [value CGRectValue].size;
        
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height + keyboardSize.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    else {
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height );
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    

}

- (void) keyboardWasHidden:(NSNotification *) notif{
    
    if (!emojiShow) {
        NSDictionary *info = [notif userInfo];
        
        NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [value CGRectValue].size;
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    else {
        CGSize bottomSize = CGSizeMake(320, toolsView.frame.size.height);
        
        [bottomView setFrame:CGRectMake(0, recordView.frame.size.height -bottomSize.height, bottomSize.width, bottomSize.height)];
    }
    
}

#pragma mark - 三方分享同步
- (IBAction)sinaShareAction:(id)sender
{
    
        
    UIButton *button = (UIButton *)sender;
    
    switch (button.tag) {
        case 0:
        {
            
            [button setImage:[UIImage imageNamed:@"gou3_yimiao_iphone.png"] forState:UIControlStateNormal];
                
             button.tag = 1;
            isAddComment = true;
           
            break;
        }
        case 1:
        {
            [button setImage:[UIImage imageNamed:@"kuang_yimiao_iphone.png"] forState:UIControlStateNormal];
 
            isAddComment = false;
            button.tag = 0;
            break;
        }
        default:
            break;
    }
    
    
    
}


@end
